﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using DTcms.Core.API.Filters;
using DTcms.Core.Common.Extensions;
using DTcms.Core.Common.Helper;
using DTcms.Core.IServices;
using DTcms.Core.Model.Models;
using DTcms.Core.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;

namespace DTcms.Core.API.Controllers
{
    [Route("auth")]
    [ApiController]
    public class AuthenticateController : ControllerBase
    {
        private readonly ITokenService _tokenService;
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly RoleManager<ApplicationRole> _roleManager;
        private readonly SignInManager<ApplicationUser> _signInManager;
        /// <summary>
        /// 构造函数依赖注入
        /// </summary>
        public AuthenticateController(
            ITokenService tokenService,
            UserManager<ApplicationUser> userManager,
            RoleManager<ApplicationRole> roleManager,
            SignInManager<ApplicationUser> signInManager)
        {
            _tokenService = tokenService;
            _userManager = userManager;
            _roleManager = roleManager;
            _signInManager = signInManager;
        }

        /// <summary>
        /// 刷新Token
        /// </summary>
        [AllowAnonymous]
        [HttpPost("retoken")]
        public async Task<IActionResult> RefreshToken([FromBody] Tokens token)
        {
            var resultDto = await _tokenService.GetRefreshTokenAsync(token.RefreshToken);
            return Ok(resultDto);
        }

        /// <summary>
        /// 用户名密码登录
        /// </summary>
        [AllowAnonymous]
        [HttpPost("login")]
        public async Task<IActionResult> Login([FromBody] LoginDto loginDto)
        {
            var resultDto = await _tokenService.LoginAsync(loginDto);
            return Ok(resultDto);
        }

        /// <summary>
        /// 手机验证码登录
        /// </summary>
        [AllowAnonymous]
        [HttpPost("login/phone")]
        public async Task<IActionResult> LoginPhone([FromBody] LoginPhoneDto loginDto)
        {
            var resultDto = await _tokenService.PhoneAsync(loginDto);
            return Ok(resultDto);
        }

        /// <summary>
        /// 重设登录密码
        /// </summary>
        [AllowAnonymous]
        [HttpPost("reset")]
        public async Task<IActionResult> ResetPassword([FromBody] PasswordResetDto modelDto)
        {
            await _tokenService.ResetAsync(modelDto);
            return NoContent();
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /*[AllowAnonymous]
        [HttpPost("register")]
        public async Task<IActionResult> Register([FromBody] RegisterDto registerDto)
        {
            //检查角色是否存在
            var role = await _roleManager.FindByIdAsync(registerDto.RoleId.ToString());
            if (role == null)
            {
                return BadRequest("指定的角色不存在");
            }
            //创建用户对象
            var user = new ApplicationUser()
            {
                UserName = registerDto.Email,
                Email = registerDto.Email,
                Status = 0
            };
            //将用户与角色关联
            user.UserRoles = new List<ApplicationUserRole>()
            {
                new ApplicationUserRole()
                {
                    RoleId=role.Id,
                    UserId=user.Id
                }
            };
            //将用户与会员或管理员信息关联
            if (role.RoleType == 0)
            {
                //如果是普通会角色则新增会员信息表
                user.Member = new Members()
                {
                    UserId = user.Id
                };
            }
            else
            {
                //否则新增管理员信息表
                user.Manager = new Manager()
                {
                    UserId = user.Id
                };
            }

            //HASH密码，保存用户
            var result = await _userManager.CreateAsync(user, registerDto.Password);
            if (!result.Succeeded)
            {
                return BadRequest(result.Errors);
            }

            return Ok();
        }*/

        /// <summary>
        /// 注销登录
        /// </summary>
        [HttpGet("logout")]
        public async Task<IActionResult> Logout()
        {
            await _signInManager.SignOutAsync();
            return NoContent();
        }
    }
}
